import urllib.request
from urllib import parse
import time

from bs4 import BeautifulSoup
'''
sudo pip3 install bs4
'''
now = time.time()  # seconds
print("start at: {}".format(now))
base_url = 'http://www.ziroom.com/z/nl/z2.html?qwd='

key_word = '博雅德园'
url = base_url + parse.quote(key_word)
print(url)

user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36'
headers = {'User-Agent': user_agent}


request = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(request)
content_b = response.read()
content = content_b.decode('utf-8')

# save file
localtime = time.localtime(now)
save_time = time.strftime("%Y%m%d%H%M%S", localtime)
milli_seconds = str(now * 1000).split('.')[0]
file_name = '/Users/ddy/ziroom' + '-' + save_time + '-' + milli_seconds + '.html'
with open(file_name, 'w+') as file:
    print("save file " + file_name)
    file.write(content)

soup = BeautifulSoup(content, 'html.parser')
no_msg = soup.find(class_='nomsgs')
if no_msg is None:
    print("yeah! has some room.")
else:
    print("there is no room in boyadeyuan.")
now_1 = time.time()
print("end at: {}".format(now_1))
cost = now_1 - now
print("cost time: {} s".format(cost))
